package com.xb.p35_simpleplayer;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.TextView;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    ImageButton btn_play,btn_pause,btn_stop;
    RadioButton radio_res,radio_sd;

    MediaPlayer player;
    int res_file=R.raw.by21;

    String sd_file="/sdcard/Music/by22.mp3";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView=findViewById(R.id.tv_name);
        btn_play=findViewById(R.id.btn_play);
        btn_pause=findViewById(R.id.btn_pause);
        btn_stop=findViewById(R.id.btn_stop);

        radio_res=findViewById(R.id.radio_res);
        radio_sd=findViewById(R.id.radio_sd);

        player=new MediaPlayer();

        //Android6.0以后需要进行的权限申请
        if(Build.VERSION.SDK_INT >= 23){
            int permission= ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (permission!= PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
            }
        }
    }

    //权限请求成功或者失败时需要进行的处理
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public void music_play(View view){
        String str="";
        if(radio_res.isChecked()){
            player=MediaPlayer.create(MainActivity.this,res_file);
            player.start();
            str=radio_res.getText().toString();
        }

        if(radio_sd.isChecked()){//从SD卡播放音乐
            player.reset();
            try {
                player.setDataSource(sd_file);
                player.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
            player.start();
            str=radio_sd.getText().toString();
        }
        textView.setText("正在播放："+str);
    }



    public void music_pause(View view){
        if (player.isPlaying()){
            player.pause();
        }else{
            player.start();
        }
    }


    public void music_stop(View view){
        if(player.isPlaying()){
            player.reset();
            player.release();
        }
    }
}